// from: https://phaser.io/js/editors/sandbox.js
/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2015 Photon Storm Ltd.
*/

/**
* Phaser Sandbox Editor functions. The modes are:
*
* 0 = preload
* 1 = create
* 2 = update
* 3 = render
* 4 = game
* 5 = help
*/
var svd = -1;
var frameReady = false;

var cursorMap = [ { "row": 0, "column": 0 }, { "row": 0, "column": 0 }, { "row": 0, "column": 0 }, { "row": 0, "column": 0 } ];
var modeMap = [ '#preload', '#create', '#update', '#render', '#game', '#help' ];
var titleMap = [ 'preload', 'create', 'update', 'render', 'PLAY', 'Help' ];

function pingGame() {

    var frame = document.getElementById('sandboxed');
    frame.contentWindow.postMessage('ping', '*');

    if (!frameReady)
    {
        window.setTimeout(pingGame, 100);
    }
    else
    {
        startGame();
    }

}

function currentInitCode() {
    var src = [
        "var game = new Phaser.Game({",
        "    type: Phaser.AUTO,",
        `    width: ${gameWidth},`,
        `    height: ${gameHeight},`,
        "    parent: 'game',",
        "    physics: {",
        "        default: 'arcade',",
        "        arcade: {",
        "            gravity: { y: 200 }",
        "        }",
        "    },",
        "    scene: {",
        "        preload: preload,",
        "        create: create,",
        "        update: update,",
        "        render: render",
        "    }",
        "});"
    ].join('\n');
    return src + '\n\n' + code;
}

function startGame() {
    //  Entering Game Mode
    console.clear();

    var frame = document.getElementById('sandboxed');
    var code_src = document.querySelector('#editor > textarea').value;
    frame.contentWindow.postMessage(code_src, '*');

}

$(document).ready(function() {
    $('#updateSize').click(function(e){
        $('#sandboxed').attr('src', './sandbox.html');

        gameWidth = $('#gameSizeW').val();
        gameHeight = $('#gameSizeH').val();

        $('#sandboxed').css('width', gameWidth);
        $('#sandboxed').css('height', gameHeight);

        window.setTimeout(startGame, 2000);
    });

    window.addEventListener('message', function (e) {

        var frame = document.getElementById('sandboxed');

        if (e.data == true)
        {
            frameReady = true;
        }

        if (e.origin === "null" && e.source === frame.contentWindow)
        {
            console.log('Result:', e.data);
        }

    });

    document.querySelector('#editor > textarea').value = currentInitCode();

    window.setTimeout(pingGame, 100);
});